package component.controls
{
	import component.controls.ui.TAScrollBar;
	import component.global.ComponentSetting;
	import component.global.manager.EventMgr;
	import component.global.manager.StageManager;
	import component.global.utils.DisplayUtils;
	import component.global.utils.ObjectUtil;
	
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.events.TextEvent;
	import flash.text.TextField;
	import flash.text.TextLineMetrics;
	
	public class TextArea extends TextInput
	{
		public function TextArea($width:int = ComponentSetting.TEXT_AREA_DEFAULT_WIDTH, $height:int = ComponentSetting.TEXT_AREA_DEFAULT_HEIGHT)
		{
			super($width,$height);
		}
		
		private var _scrollBar:TAScrollBar;
		private var _scrollBarEnabled:Boolean;
		private var _currentScrollV:int = 1;
		private var _maxScrollV:int = 1;
		private var _mouseDownIdx:int; 
		private var _selectionLength:int;
		
		override protected function init():void{
			super.init();
			_textField.wordWrap = _textField.multiline = true;
			_textField.mouseWheelEnabled = false;
			_scrollBar = new TAScrollBar(_background.height);
			_scrollBar.targetDisplay = this;
			EventMgr.Instance.addEvent(_textField,[Event.SCROLL,Event.CHANGE,MouseEvent.MOUSE_WHEEL],[__onScroll,__onChange,__onMouseWheel]);
		}
		
		public function get textField():TextField{
			return _textField;
		}
		
		public function set scrollBarEnabled(value:Boolean):void{
			if(_scrollBarEnabled == value)return;
			_scrollBarEnabled = value;
			if(_scrollBarEnabled){
				_textField.width -= _scrollBar.width;
				_scrollBar.x = _background.width - _scrollBar.width;
				DisplayUtils.addDisplayObject(this, _scrollBar);
			} else {
				_textField.width += _scrollBar.width;
				DisplayUtils.removeDisplay(_scrollBar);
			}
		}
		
		private function __onScroll(e:Event):void{
			_scrollBar.updateThumb();
		}
		
		private function __onChange(e:Event):void{
			if(_maxScrollV > _textField.maxScrollV){
				_textField.scrollV = _textField.scrollV - (_maxScrollV - _textField.maxScrollV);
			}
			_maxScrollV = _textField.maxScrollV;
			
			if(_textField.maxScrollV > 1){
				scrollBarEnabled = true;
				if(_textField.maxScrollV <= 1){
					_scrollBar.enabled = false;
				} else {
					_scrollBar.enabled = true;
				} 
			} else {
				scrollBarEnabled = false;
			}
		}
		
		private function __onMouseWheel(e:MouseEvent):void{
			if(e.delta > 0 && _scrollBar.scrollPos > 0){
				_scrollBar.scrollTo(_scrollBar.scrollPos - 1);
			} 
			if(e.delta < 0 && _scrollBar.scrollPos < _textField.maxScrollV - 1){
				_scrollBar.scrollTo(_scrollBar.scrollPos + 1);
			}
		}

		override public function dispose():void{
			super.dispose();
			EventMgr.Instance.removeEvent(this);
			EventMgr.Instance.removeEvent(_textField);
			ObjectUtil.dispose(_scrollBar);_scrollBar=null;
		}
	}
}